import React, { PureComponent } from "react";

import { connect } from "react-redux";

class App extends PureComponent {
  render() {
    let { inputValue, inputChange, clickButton, deleteItem } = this.props;
    return (
      <div>
        <input type="text" value={inputValue} onChange={(e) => inputChange(e)} />
        <button
          onClick={(e) => {
            clickButton();
          }}
        >
          提交
        </button>
        <ul>
          {this.props.list.map((item, index) => {
            return (
              <li
                key={index}
                onClick={(e) => {
                  deleteItem(e, index);
                }}
              >
                {item}
              </li>
            );
          })}
        </ul>
      </div>
    );
  }
}

// 映射成属性
const stateToProps = (state) => {
  return {
    inputValue: state.inputValue,
    list: state.list,
  };
};

const dispatchToProps = (dispatch) => {
  return {
    inputChange(e) {
      let action = {
        type: "change_input",
        value: e.target.value,
      };
      // 派发action
      dispatch(action);
    },
    clickButton() {
      let action = { type: "add_item" };
      dispatch(action);
    },

    // 删除
    deleteItem(e, index) {
      console.log("删除: ", index);
      let action = { type: "delete_item", index };
      dispatch(action);
    },
  };
};

export default connect(stateToProps, dispatchToProps)(App);
